package com.yc.forum.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

//@WebFilter(filterName = "LoginFilter")
@WebFilter({"/personal.html","/putpost/add-post.html","/Modify.html","/putpost/AskProblem.html"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }
//过滤器
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        HttpSession session=req.getSession();
        //获取被拦截页面地址
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String servletPath = httpServletRequest.getServletPath();
        String loginHtml="login.html";
        loginHtml = URLEncoder.encode(loginHtml,"utf-8");
//       判断 访问分页的目录级别
        if(session.getAttribute("loginedUser")==null){
            if(servletPath.split("/").length==3){
                resp.sendRedirect("../"+loginHtml);
            }else {
                resp.sendRedirect(loginHtml);
            }
            return;
        }
        chain.doFilter(request, response);
    }
}
